@page "/database-connection"
@using SqlSugar
@using Text2Sql.Net.Domain.Model
@using Text2Sql.Net.Repositories.Text2Sql.DatabaseConnection
@using Text2Sql.Net.Repositories.Text2Sql
@inject IDatabaseConnectionConfigRepository DatabaseConnectionConfigRepository
@inject MessageService MessageService
@inject NavigationManager NavigationManager

<PageContainer Title="数据库连接管理">
    <Extra>
        <Button Type="primary" Icon="plus" @onclick="NavigateToCreate">
            创建连接
        </Button>
    </Extra>
    <Content>
        <div class="search-container">
            <Search Placeholder="请输入连接名称"
                    EnterButton="@("搜索")"
                    Style="max-width: 522px; width: 100%;"
                    OnSearch="Search" />
        </div>
    </Content>
    <ChildContent>
        <Spin Spinning="@_loading">
            <div class="card-list-container">
                <Row Gutter="24">
                    @foreach (var item in _dataList.Where(x => !string.IsNullOrEmpty(x.Id)))
                    {
                        <AntDesign.Col Xs="24" Sm="12" Md="12" Lg="6" Xl="6" XXl="6">
                            <Card Hoverable Bordered Class="connection-card"
                                  Actions="@(new[] {
                                                info(() => NavigateToDetails(item.Id)),
                                                update(() => NavigateToEdit(item.Id)),
                                                delete(() => DeleteConnection(item.Id))
                                            })">
                            <CardMeta>
                                <AvatarTemplate>
                                        <Avatar Size="large" Icon="database" Style="background-color:#1890ff" />
                                </AvatarTemplate>
                                <TitleTemplate>
                                    <div class="card-title">@item.Name</div>
                                </TitleTemplate>
                                <DescriptionTemplate>
                                    <div class="card-description">
                                        <Tag Color="@GetDbTypeColor(item.DbType)">@item.DbType</Tag>
                                        <div class="create-time">创建时间: @(item.CreateTime.ToString("yyyy-MM-dd"))</div>
                                    </div>
                                </DescriptionTemplate>
                            </CardMeta>
                        </Card>
                    </AntDesign.Col>
                    }
                </Row>
                
                @if (!_dataList.Any() || _dataList.Count == 1 && string.IsNullOrEmpty(_dataList[0].Id))
                {
                    <Empty Description="@("暂无数据连接")">
                        <Button Type="primary" Icon="plus" @onclick="NavigateToCreate">
                            创建连接
                        </Button>
                    </Empty>
                }
            </div>
        </Spin>
    </ChildContent>
</PageContainer>

<style>
    .search-container {
        text-align: center;
    }
    
    .card-list-container {
        padding: 24px;
        background-color: #f0f2f5;
        border-radius: 8px;
        min-height: 300px;
    }
    
    .connection-card {
        border-radius: 8px;
        transition: all 0.3s;
        height: 100%;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
    }
    
    .connection-card:hover {
        box-shadow: 0 8px 16px rgba(24, 144, 255, 0.2);
        transform: translateY(-4px);
        border-color: #1890ff;
    }
    
    .card-title {
        font-size: 16px;
        font-weight: 500;
        color: rgba(0, 0, 0, 0.85);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    
    .card-description {
        margin-top: 12px;
    }
    
    .create-time {
        margin-top: 8px;
        font-size: 12px;
        color: rgba(0, 0, 0, 0.45);
    }
</style>

@code {
    RenderFragment info(Action clickAction) =>@<a key="info" @onclick="@clickAction">查看</a>;
    RenderFragment update(Action clickAction) =>@<a key="use" @onclick="@clickAction">编辑</a>;
    RenderFragment delete(Action clickAction) => @<a key="delete" @onclick="@clickAction">删除</a> ;


    private List<DatabaseConnectionConfig> _dataList = new List<DatabaseConnectionConfig>();
    private bool _loading = false;
    private int _total = 0;

    protected override async Task OnInitializedAsync()
    {
        await InitData("");
    }

    private async Task InitData(string searchKey)
    {
        _loading = true;
        try
        {
            var exp = Expressionable.Create<DatabaseConnectionConfig>();
            exp.AndIF(!string.IsNullOrEmpty(searchKey), p => p.Name.Contains(searchKey));
            var data = await DatabaseConnectionConfigRepository.GetListAsync(exp.ToExpression());
            _dataList = data.OrderByDescending(x => x.CreateTime).ToList();
            _total = _dataList.Count;
        }
        catch (Exception ex)
        {
            await MessageService.Error($"加载数据失败: {ex.Message}", 2);
        }
        finally
        {
            _loading = false;
            await InvokeAsync(StateHasChanged);
        }
    }

    private async Task Search(string searchKey)
    {
        await InitData(searchKey);
    }

    private void NavigateToCreate()
    {
        NavigationManager.NavigateTo($"/database-connection/create");
    }

    private void NavigateToDetails(string id)
    {
        NavigationManager.NavigateTo($"/database-connection/details/{id}");
    }

    private void NavigateToEdit(string id)
    {
        NavigationManager.NavigateTo($"/database-connection/create/{id}");
    }

    private async Task DeleteConnection(string id)
    {
        try
        {
            var success = await DatabaseConnectionConfigRepository.DeleteAsync(id);
            if (success)
            {
                await MessageService.Success("删除成功");
                await InitData("");
            }
            else
            {
                await MessageService.Error("删除失败");
            }
        }
        catch (Exception ex)
        {
            await MessageService.Error($"删除失败: {ex.Message}");
        }
    }
    
    private string GetDbTypeColor(string dbType)
    {
        return dbType?.ToLower() switch
        {
            "mysql" => "green",
            "sqlserver" => "blue",
            "oracle" => "red",
            "postgresql" => "purple",
            "sqlite" => "orange",
            "dm" => "cyan",
            "kingbasees" => "gold",
            "clickhouse" => "volcano",
            "opengauss" => "magenta",
            _ => "geekblue"
        };
    }
} 